package lerry.nape.utils;

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import nape.geom.AABB;

/**
 * ...
 * @author ...
 * 2013/10/30 17:31
 */

#if flash
class DisplayObjectISO implements nape.geom.IsoFunction {
#else
class DisplayObjectISO {
#end
	var disObj:DisplayObject;
	var at:Float;
	public var bounds:AABB;
	public function new(obj:DisplayObject,alphaThreshold:Float=0x80){
		disObj=obj;
		bounds = new AABB(obj.x, obj.y, obj.width, obj.height);
		at=alphaThreshold;
	}
	public function iso(x:Float, y:Float):Float {
		if (Std.is(disObj, Bitmap)) {
			var ix = Std.int(x); if(ix<0) ix = 0; else if(ix>=disObj.width)  ix = Std.int(disObj.width -1);
			var iy = Std.int(y); if(iy<0) iy = 0; else if(iy>=disObj.height) iy = Std.int(disObj.height-1);
			var fx = x - ix; if(fx<0) fx = 0; else if(fx>1) fx = 1;
			var fy = y - iy; if(fy<0) fy = 0; else if(fy>1) fy = 1;
			var gx = 1-fx;
			var gy = 1-fy;
			var data:BitmapData=cast(disObj,Bitmap).bitmapData;
			var a00 = data.getPixel32(ix,iy)>>>24;
			var a01 = data.getPixel32(ix,iy+1)>>>24;
			var a10 = data.getPixel32(ix+1,iy)>>>24;
			var a11 = data.getPixel32(ix+1,iy+1)>>>24;

			var ret = gx*gy*a00 + fx*gy*a10 + gx*fy*a01 + fx*fy*a11;
			return 0x80 - ret;
		}
		return (disObj.hitTestPoint(x,y,true) ? -1.0 : 1.0);
		return .1;
    }
	public function dispose():Void {
		disObj = null;
		bounds = null;
	}
}


